package com.handu.open.dubbo.monitor.interceptor;


import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.util.Properties;

/**
 * DialectStatementHandlerInterceptor.java
 */
@Slf4j
@Intercepts(
        {@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
         @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class DialectStatementHandlerInterceptor implements Interceptor {

    private String showSql;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //获取执行参数
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        BoundSql boundSql=ms.getSqlSource().getBoundSql(objects[1]);;
        if ("true".equals(showSql)) {
            log.info("Executing SQL: {}", boundSql.getSql().replaceAll("\\s+", " "));
            log.info("\twith params: {}", boundSql.getParameterObject());
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        this.showSql =properties.getProperty("showSql");
    }
}
